const DB = require('../db');
const emailLogic = require('./email');
const mongoose = require('mongoose');


async function save(keyword) {
    return new DB.Keyword(keyword).save()
}

async function query(pageNum = 1, pageCount = 10, filter) {
    pageNum = Number(pageNum);
    pageCount = Number(pageCount);
    return await DB.Keyword
        .find(filter)
        .limit(pageCount)
        .skip((pageNum - 1) * pageCount)
        .select()
}

async function queryAll() {
    let keywords = await DB.Keyword
        .find({
            state: 1
        })
        .select();
    for (const keyword of keywords) {
        let emails = await emailLogic.queryByIds(keyword.emailIds);
        keyword.emails = emails;
    }
    return keywords;
}

async function queryById(id) {
    return DB.Keyword.findById(id);
}

async function total() {
    return DB.Keyword.countDocuments({
        state: 1
    });
}

async function removeEmail(keywordId, emailId) {
    return DB.Keyword.updateOne({
        _id: keywordId
    }, { $pull: { emailIds: emailId } })
}


async function update(keyword) {
    if (Array.isArray(keyword.emailIds)) {
        keyword.emailIds = keyword.emailIds.map(mongoose.Types.ObjectId);
    } else {
        keyword.emailIds = [];
    }
    return DB.Keyword.updateOne({
        _id: keyword._id
    }, {
        name: keyword.name,
        words: keyword.words,
        emailIds: keyword.emailIds
    })
}

async function remove(id) {
    return DB.Keyword.updateOne({
        _id: id
    }, {
        state: 0
    })
}

module.exports = {
    save,
    query,
    total,
    queryAll,
    queryById,
    removeEmail,
    update,
    remove
}